package com.restphp.java.utils.mysql.builder.core;

import com.restphp.java.utils.mysql.builder.po.NativePo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据值操作拼接器.
 * Created by sofical on 2020/6/12.
 */
public class SqlValuesUtils {
    private Map<String, Object> valueMap = new HashMap<>();

    /**
     * 设置查询数据操作值.
     * @param column 列.
     * @param value 值.
     * @return 数据值操作拼接器.
     */
    public SqlValuesUtils set(String column, Object value) {
        this.valueMap.put(column, value);
        return this;
    }

    /**
     * 设置查询数据操作值（兼容旧模式）.
     * @param map 列=>值 map 对象.
     * @return 数据值操作拼接器.
     */
    public SqlValuesUtils set(Map<String, Object> map) {
        this.valueMap.putAll(map);
        return this;
    }

    /**
     * 拼接新增SQL语句.
     * @return 新增SQL语句.
     */
    public NativePo getInsert() {
        String sqlColumn = "";
        String sqlValueSpace = "";
        List<Object> values = new ArrayList<>();
        for (Map.Entry<String, Object> entry : this.valueMap.entrySet()) {
            sqlColumn += ("".equals(sqlColumn) ? "" : ", ") + entry.getKey();
            sqlValueSpace += ("".equals(sqlValueSpace) ? "" : ", ") + "?";// + entry.getKey();
            values.add(entry.getValue());
        }
        String sql = "(" + sqlColumn + ") values (" + sqlValueSpace + ")";
        NativePo nativePo = new NativePo();
        nativePo.setSql(sql);
        nativePo.setValues(values);
        return nativePo;
    }

    /**
     * 拼接更新SQL语句.
     * @return 更新SQL语句.
     */
    public NativePo getUpdate() {
        String sql = "";
        List<Object> values = new ArrayList<>();
        for (Map.Entry<String, Object> entry : this.valueMap.entrySet()) {
            sql += ("".equals(sql) ? "" : ", ") + entry.getKey() + "=?"; // + entry.getKey();
            values.add(entry.getValue());
        }
        NativePo nativePo = new NativePo();
        nativePo.setSql(sql);
        nativePo.setValues(values);
        return nativePo;
    }
}
